
Ext.namespace('business.equipment.ecsb');

	// 主页面
	business.equipment.ecsb.MailViewer = Ext.extend(Ext.Panel, {
		
		/**
		 * 设备基本信息
		 */ 
		detailInfo  : null,

		/**
		 * 设备工作记录列表
		 */ 
		workRecord   : null,
		
		border      : false,

		/**
	     * 初始化
		 */
		initComponent : function() {
			
			var obj = this;
			
			this.addListener('render', function() {
				obj.startViewer.defer(1, obj);
			});

			this.layout	= 'fit';
			
			business.equipment.ecsb.MailViewer.superclass.initComponent.call(this);
		},
		
		/**
		 * 初始化顺序处理
		 */
		startViewer : function() {
			
			// 初始化页面
			this.renderViewer();
			// grid绑定菜单
			this.workRecord.menuCreate();

		},
		
		/**
		 * 加载控件
		 */
		renderViewer : function() {

			var obj = this;

			//----------------------------------------------------------------------
			//	设备基本信息
			//----------------------------------------------------------------------
			this.detailInfo = new business.equipment.ecsb.DetailInfo({
				id                  : 'detailinfo',
				layout              : 'fit',
				title               : '基本信息、参数'

			});

			//----------------------------------------------------------------------
			//	设备工作记录列表
			//----------------------------------------------------------------------
			this.workRecord = new business.equipment.ecsb.WorkRecord({
				id                  : 'workrecord',
				layout              : 'fit',
				title               : '设备工作记录列表',
				actived             : false
			});
	
			//----------------------------------------------------------------------
			//	主页面 0 ：基本信息 1：设备工作记录列表
			//----------------------------------------------------------------------
			var viewer = new Ext.TabPanel({
				items 		: [obj.detailInfo, obj.workRecord],
				activeTab   : 0
			});
			
			//----------------------------------------------------------------------
			//	tab激活时加载列表数据
			//----------------------------------------------------------------------			
			viewer.on('tabchange' , function (Tabs, tab) {
				
				if (tab.id != 'detailinfo' && sbid == '0') {
					Ext.MessageBox.alert('提示', '请先保存基本信息');
					viewer.setActiveTab(0);
					return;
				}

				// 应用菜单
				if (tab.id == 'workrecord') {

					if (tab.actived == false) {
						tab.actived = true;
						//obj.workRecord.gridstore.reload();
					} 
				} 
			});

			this.add(viewer);

			if ((typeof this.layout) == "object") this.doLayout();

		}
		
	});

	/**
	 * 基本信息
	 */
	business.equipment.ecsb.DetailInfo = Ext.extend(Ext.Panel, {
		
		detail        : null,
		
		/**
		 * 全部的装置类型2
		 */
		zzlxSon       : null,

		/**
	     * 初始化
		 */
		initComponent : function() {

			var obj = this;
			
			obj.zzlxSon =  new Ext.data.Store(
								{
									proxy : new Ext.data.HttpProxy({
									url : 'dic!getDicJson.do?dic.itemType=ECSBZZLX2'
								}),
								reader : new Ext.data.JsonReader({}, ['itemId', 'itemName', 'remark']),
								autoLoad : true
							});

			//----------------------------------------------------------------------
			//	详细信息页面
			//----------------------------------------------------------------------
			this.detail = new Ext.form.FormPanel({
				id : 'ecsb_detail',
				bodyStyle  : 'padding: 10px; background-color: #DFE8F6',
				method :'POST',
				frame  : true,
				labelAlign:'right',
				tbar :[
					{
						text:'保存',
						icon:contextpath + "/images/save2.gif",
						hidden:btn_save,
						handler: function() {
        					obj.submit();
        				}
					},'-',{
						text:'变电站选择',
						icon:contextpath + "/images/pass.gif",
						hidden:btn_save,
						handler: function() {
        					winbdztree.win.openCommentWindow();
        				}
					}
				],
		        items: [
		        	{
		        		xtype : 'fieldset',   
		        		layout : 'form',
		        		title : '基本信息',
		        		items : [
			        	{
	        				layout:'column',
	        				items:[
	        					{	
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										xtype : 'textfield',
										fieldLabel :'装置名称',
		                				anchor: '90%',
				            			name: 'entity.zzmc',
				            			id : 'entity.zzmc',
			            				maxLength :25
	        						}]
	        					}, {	
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										fieldLabel :'装置类型1',
										name :'sblx',
										id : 'sblx',
										xtype : 'combo',
		                				anchor: '90%',
										hiddenName : 'entity.sblx',
										store : new Ext.data.Store({
											proxy : new Ext.data.HttpProxy({
												url : 'dic!getEquipDicJson.do?dic.itemType=SBLX2'
											}),
											reader : new Ext.data.JsonReader({}, ['itemId', 'itemName']),
											autoLoad : true,
											listeners:{
					              				load: function(combo, record, index) {
					              					var r = new Ext.data.Record({itemId:'', itemName:''});
													// 选中默认装置类型1
													Ext.getCmp('sblx').store.insert(0,r);
													Ext.getCmp('sblx').store.each(function(item) {
														if (item.get('itemId') == Ext.getCmp('sblx').getValue()) {
															Ext.getCmp('sblx').setRawValue(item.get('itemName'));
														}
													});	
					 							}
					          				}
										}),
										displayField : 'itemName',
										valueField : 'itemId',
										forceSelection : true,
										selectOnFocus : true,
										editable : false,
										triggerAction : 'all',
										mode : 'local',//'remote',
										allowBlank : false,
										emptyText:'请选择',
										listeners:{
				              				'select': function(combo, record, index) {
				              					Ext.getCmp('zzlx2').store.removeAll();
				              					var r = new Ext.data.Record({itemId:'', itemName:''});
												Ext.getCmp('zzlx2').store.insert(0,r);
												Ext.getCmp('zzlx2').setValue('');
												Ext.getCmp('zzlx2').setRawValue('');
				              					obj.zzlxSon.each(function(item) {
				              						if (item.get('itemId').indexOf(combo.getValue()) != -1) {
				              							Ext.getCmp('zzlx2').store.add(item);
				              						}
				              					})
				 							}
				          				}
									}]
	        					}, {	
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										fieldLabel :'装置类型2',
										name :'zzlx2',
										id : 'zzlx2',
										xtype : 'combo',
		                				anchor: '90%',
										hiddenName : 'entity.zzlx2',
										displayField : 'itemName',
										valueField : 'itemId',
										store      : new Ext.data.Store(),
										forceSelection : true,
										selectOnFocus : true,
										editable : false,
										triggerAction : 'all',
										mode : 'local',
										//allowBlank : false,
										emptyText:'请选择'
	
									}]
	        					}
	            			]
			        	},{
	        				layout:'column',
	        				items:[
	        					{	
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										xtype : 'textfield',
										fieldLabel :'变电站',
		                				anchor: '90%',
				            			name: 'bdzname',
				            			id : 'bdzname',
										allowBlank : false,
            							style:'background:#f0f0f0',
			            				readOnly:true
	        						}]
	        					}, {
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										xtype : 'textfield',
										fieldLabel :'所属屏柜',
		                				anchor: '90%',
				            			name: 'typename',
				            			id : 'typename',
										allowBlank : false,
	            						style:'background:#f0f0f0',
				            			readOnly:true
	
									}]
	        					}, {	

	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										fieldLabel :'电压等级',
										name :'dydj',
										id : 'dydj',
										xtype : 'combo',
		                				anchor: '90%',
										hiddenName : 'entity.dydj',
										store : new Ext.data.Store({
											proxy : new Ext.data.HttpProxy({
												url : 'dic!getDicJson.do?dic.itemType=DYDJ'
											}),
											reader : new Ext.data.JsonReader({}, ['itemId', 'itemName']),
											autoLoad : true
										}),
										displayField : 'itemName',
										valueField : 'itemId',
										forceSelection : true,
										selectOnFocus : true,
										editable : false,
										triggerAction : 'all',
										mode : 'local',
										allowBlank : false,
										emptyText:'请选择'
	        						}]
	        					}]
			        	},{
	        				layout:'column',
	        				items:[
	        					{	
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										xtype : 'textfield',
										fieldLabel :'装置型号',
		                				anchor: '90%',
				            			name: 'entity.zzxh',
				            			id : 'entity.zzxh',
										allowBlank : false,
										maxLength :25
	        						}]
	        					}, {
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										xtype : 'textfield',
										fieldLabel :'软件版本号',
		                				anchor: '90%',
				            			name: 'entity.rjbbh',
				            			id : 'entity.rjbbh',
										//allowBlank : false,
										maxLength :25
	        						}]
	        					}, {	
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										xtype : 'datefield',
										format:'Y-m-d',
										fieldLabel :'程序生成时间',
		                				width:100,
		                				//editable: false,
		                				//allowBlank : false,
				            			name: 'entity.cxscsj',
				            			id : 'entity.cxscsj'
	        						}]
	        					}]
			        	},{
	        				layout:'column',
	        				items:[
	        					{	
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										xtype : 'textfield',
										fieldLabel :'校验码',
		                				anchor: '90%',
				            			name: 'entity.jym',
				            			id : 'entity.jym',
										//allowBlank : false,
										maxLength :25
	        						}]
	        					}, {
	        						layout:'form',
	        						columnWidth:.3,
	        						items:[{
										xtype : 'datefield',
										format:'Y-m-d',
										fieldLabel :'生产日期',
		                				width:100,
		                				editable: false,
		                				//allowBlank : false,
				            			name: 'entity.ccrq',
				            			id : 'entity.ccrq'
	        						}]
	        					}]
	        			}, {
	        				layout:'column',
	        				items:[
	        					{	
	        						layout:'form',
	        						columnWidth:.6,
	        						items:[{
										xtype : 'textfield',
										fieldLabel :'生产厂家',
		                				anchor: '90%',
				            			name: 'entity.sccj',
				            			id : 'entity.sccj',
										//allowBlank : false,
										maxLength :100
	        						}]
	        					}]
	        			}, {
	        				layout:'column',
	        				items:[
	        					{	
	        						layout:'form',
	        						columnWidth:.6,
	        						items:[{
										xtype : 'textfield',
										fieldLabel :'备注',
		                				anchor: '90%',
				            			name: 'entity.bz',
				            			id : 'entity.bz',
										//allowBlank : false,
										maxLength :100
	        						}]
	        					}]
	        				}]
		        	},{	
            			xtype: 'hidden',
            			name: 'entity.id',
            			id:'entity.id',
						value:'0'
        			},{
            			xtype: 'hidden',
            			name: 'entity.modelid',
            			id:'entity.modelid',
            			value:'0'
        			},{
            			xtype: 'hidden',
            			name: 'entity.bdzid',
            			id:'entity.bdzid'
        			},{
            			xtype: 'hidden',
            			name: 'entity.typeid',
            			id:'entity.typeid'
        			},{
            			xtype: 'hidden',
            			name: 'entity.state',
            			id:'entity.state'
        			}
		   	   ]
			});

			//----------------------------------------------------------------------
			//	加载数据
			//----------------------------------------------------------------------
			this.loadData();
			
			this.items = [this.detail];

			business.equipment.ecsb.DetailInfo.superclass.initComponent.call(this);

		},
		
		/**
		 * 提交保存
		 */
		submit: function() {
			
			var obj = this;

			// 验证有效性
        	if (!obj.detail.getForm().isValid()) {
        		return;
        	} 
			
			// 提交
			obj.detail.getForm().submit({
				waitMsg :'保存中...',
				url:'equip!save.do',
				success : function(form, action) {
					Ext.MessageBox.alert('提示', action.result.msg);
					if (!Ext.isEmpty(action.result.paraid)) {
						Ext.getCmp('entity.id').setValue(action.result.id);
						Ext.getCmp('entity.modelid').setValue(action.result.modelid);
						sbid = action.result.id;
						parent.mailViewer.sb.gridstore.reload();
					}
				},
				failure : function(action) {
					Ext.MessageBox.alert('提示', '保存失败。');
				}
			});
		},

		/**
		 * 加载数据
		 */
		loadData :function () {
		
			var obj = this;			
			// 新建时
			if (sbid == '0') {
				Ext.getCmp('entity.state').setValue(parent.mailViewer.state);
				Ext.getCmp('entity.bdzid').setValue(parent.mailViewer.bdzid);
				Ext.getCmp('entity.typeid').setValue(parent.mailViewer.typeid);
				Ext.getCmp('bdzname').setValue(parent.mailViewer.bdzname);
				Ext.getCmp('typename').setValue(parent.mailViewer.typename);
				
				// 修改时
		    } else {

				Ext.Ajax.request({
					method :'POST',
					url :'equip!initBaseInfo.do',
					params : {
						id : sbid,
						modelid:modelid
					},
					success : function(response, options) { 

						var rtn = Ext.decode(response.responseText);
						
						// 基本信息参数
						for (var p in rtn[0]) {
							try {
								obj.detail.getForm().findField("entity." + p).setValue(rtn[0][p]);
							} catch (e){
							}
						}
						obj.detail.getForm().findField("entity.dydj").setRawValue(rtn[0]["dydj"] + 'kV');
						obj.detail.getForm().findField("bdzname").setRawValue(bdzname);
						obj.detail.getForm().findField("typename").setRawValue(typename);
						
						obj.zzlxSon.on('load', function() {
					              					
          					// 装置类型2 增加空项目
							var r = new Ext.data.Record({itemId:'', itemName:''});
          					Ext.getCmp('zzlx2').store.removeAll();
							Ext.getCmp('zzlx2').store.insert(0,r);
          					obj.zzlxSon.each(function(item) {
          						if (item.get('itemId').indexOf(Ext.getCmp('sblx').getValue()) != -1) {
          							Ext.getCmp('zzlx2').store.add(item);
          							if (item.get('itemId') == Ext.getCmp('zzlx2').getValue()) {
          								Ext.getCmp('zzlx2').setRawValue(item.get('itemName'));
          							}
          						}
          					})
						});

					},
					failure : function() {
						Ext.MessageBox.alert('提示 ', '提取数据失败！');
					}
				});

		    }
		}
	
	});
	
	/**
	 * 其他列表信息
	 */
	business.equipment.ecsb.WorkRecord = Ext.extend(Ext.Panel, {
		
		actived   : false,
		
		/**
		 * 设备工作记录列表
		 */
		grid      : null,
		
		/**
		 * 设备工作记录列表
		 */
		gridstore : null,

		/**
	     * 初始化
		 */
		initComponent : function() {

			var obj = this;

			//----------------------------------------------------------------------
			//	列表数据源
			//----------------------------------------------------------------------
			this.gridstore = new Ext.data.Store({
				proxy :new Ext.data.HttpProxy({
					url :'equip!getEquipList.do'
				}),
				reader :new Ext.data.JsonReader({
					root :'result',
					totalProperty :'totalCount',
					fields : ['id', 'bdzname', 'bdzid', 'typename', 'dydjname', 'sblxname', 'tyrq', 'state']
				}),
				autoLoad:false,
				remoteSort :false
			});

			//----------------------------------------------------------------------
			//	加载列表
			//----------------------------------------------------------------------
			this.grid = new Ext.grid.GridPanel({
				id					: "ecsb_grid",
				store 				: obj.gridstore,
				layout 				: 'fit',
				enableDragDrop		: false,
				stripeRows			: true,
				animCollapse		: false,
				cm: new Ext.grid.ColumnModel({
	        		defaults: {
	            		sortable: true
	        		},
	        		columns: [
	        			new Ext.grid.RowNumberer(),
	            		//sm,
						{	id:'id',
							header :"序号",
							width :50,
							dataIndex :'id',
							sortable :true,
							hidden :true
						}, {
							header :"变电站",
							width :70,
							dataIndex :'bdzname',
							sortable :true,
							align:'center'
						}, {
							header :"隔断、瓶柜",
							width :70,
							dataIndex :'typename',
							sortable :true,
							align:'center'
						},{
							header :"设备类型",
							width :120,
							dataIndex :'sblxname',
							sortable :true,
							align:'center'
						},{
							header :"电压等级",
							dataIndex :'dydjname',
							sortable :true,
							align:'center'
						},{
							header :"投运日期",
							width :120,
							dataIndex :'tyrq',
							sortable :true,
							align:'center'
						}]
				}),
				selModel  : new Ext.grid.RowSelectionModel({singleSelect : true}),
				loadMask : {
					msg :'载入中,请稍候...'
				},
				viewConfig:{
					forceFit:true
				},
				tbar :[
					{
						id :'ecsb_query',
						text :'刷新',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/page_find.png',
			            handler:function() {
			            	obj.gridstore.reload();
        				}
					}, btn_insert ? '' : '-',{
						id :'ecsb_insert',
						text :'新建',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/add.gif',
        				hidden:btn_insert
					}, btn_delete ? '' : '-',{
						id :'ecsb_delete',
						text :'删除',
						cls:'x-btn-text-icon',
        				icon:contextpath + '/images/delete.gif',
        				hidden:btn_delete,
        				handler:function() {
        					obj.deleteWorkRecord();
        				}
					}
				],
				bbar : new Ext.PagingToolbar({
					store : obj.gridstore,
					pageSize:100,
					displayInfo :true,
					displayMsg :'共 {2} 条',
					emptyMsg :"没有数据显示！"
				}),
				listeners:{'rowdblclick':function(row) {
					//obj.getDetail();
				}}
			});

			this.items = [
				this.grid
			]

			business.equipment.ecsb.WorkRecord.superclass.initComponent.call(this);
		
		},
	
		/**
		 * 菜单绑定
		 */
		menuCreate: function (){

			var obj = this;

			var actEdit = new Ext.Action({
				id			: 'menu_edit',
				text		: '修改',
				tooltip		: '修改当前间隔',
				iconCls		: 'icon_edit',
				handler		: function() { obj.getDetail()}
			});

			var actDelete = new Ext.Action({
				id			: 'menu_delete',
				text		: '删除',
				tooltip		: '删除当前间隔',
				iconCls		: 'icon_delete',
				hidden      : btn_delete,
				handler		: function() { obj.deleteWorkRecord()}
			});
			
			obj.commandMenu = new Ext.menu.Menu({
				minWidth	: 160,
				items	: [
					actEdit, '-',
					actDelete
				]
			});
			
			obj.grid.on('rowcontextmenu',function (grid, rowIndex, e) {
      			e.preventDefault();
      			obj.grid.getSelectionModel().selectRow(rowIndex);
        		obj.commandMenu.showAt(e.getXY());   
			});
			
		},

		/**
		 * 删除
		 */
		deleteWorkRecord: function() {
			
//			var obj = this;
//			
//			if (!obj.grid.getSelectionModel().hasSelection()) {
//				Ext.MessageBox.alert("提示","请先选择要删除的记录");
//				return;
//			}
//			
//			var ids = obj.grid.getSelectionModel().getSelected()['data']['id'];
//			
//			Ext.MessageBox.confirm('提示', '确定要删除选中的【' + obj.grid.getSelectionModel().getSelected()['data']['jgmc'] + '】记录吗？', function (btn) {
//				
//				if (btn == 'yes') {
//
//					Ext.Ajax.request({
//						method :'POST',
//						url :'equip!deleteJg.do',
//						params : {
//							id :ids
//						},
//						success : function(response) {
//							
//							Ext.MessageBox.alert('提示', response.responseText, function () {
//								obj.grid.store.reload();
//							});
//						},
//						failure : function() {
//							Ext.MessageBox.alert('提示', '删除失败！');
//						}
//					});
//				}
//
//			});
			
		},
		
		/**
		 * 新建时
		 */
		insertWorkRecord: function(id) {
			//this.fireEvent('addTab', sblx, sblxname);
		}
	
	});